﻿using AutoMapper;
using B.S.BasicData.Api.Read.Application.Command.Approval;
using B.S.BasicData.Api.Read.DTOS;
using B.S.BasicData.Domain.Entity.Approval;
using B.S.BasicData.Domian.Entitys;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infastructure.Interface;
using MediatR;

namespace B.S.BasicData.Api.Read.Application.Handler.Approval
{
    public class GetDeparmentHandler : IRequestHandler<GetDeparmentCommand, ApiResult<List<DeparmentDto>>>
    {
        private readonly IBaseRepository<UsersModel> _userRepository;
        private readonly IBaseRepository<DeparmentModel> _deparmentRepository;
        private readonly IMapper _mapper;

        public GetDeparmentHandler(IBaseRepository<DeparmentModel> deparmentRepository, IMapper mapper, IBaseRepository<UsersModel> userRepository)
        {
            _deparmentRepository = deparmentRepository;
            _mapper = mapper;
            _userRepository = userRepository;
        }

        /// <summary>
        /// 根据用户获取部门信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task<ApiResult<List<DeparmentDto>>> Handle(GetDeparmentCommand request, CancellationToken cancellationToken)
        {
            ApiResult<List<DeparmentDto>> result = new ApiResult<List<DeparmentDto>>();
          
            //根据登录人Id获取用户数据中的部门Id
            var Did = _userRepository.GetAll().Where(p=>p.Id==request.Uid).Select(p=>p.DeparmentId).FirstOrDefault();
            //用获取到的部门Id获取部门数据
            var deparment = _deparmentRepository.GetAll().Where(p=>p.Id==Did).ToList();

            result.Code = StatusEnum.OK;
            result.Data = _mapper.Map<List<DeparmentDto>>(deparment);
            result.Message = "获取成功";
            return Task.FromResult(result);

        }
    }
}
